<?
/*
Galaxy
Author:McFog
*/
defined('IN GALAXY') or exit('McFog');

class view_common {
	protected $data, $tplname , $userpack = array('templates.lang.php');
		
	function __construct($tplname, $data = array(), $userpack = array('templates.lang.php')) {
		//galaxy::extract_to(get_defined_vars(), $this);
		foreach(array('tplname', 'data', 'userpack') as $v)
			$this->$v = $$v;
	}
	function show() {
		extract($this->mkENV());
		@extract($this->data);
		header("Content-Type: text/html; charset=utf-8");
		include $this->template($this->tplname, $this->userpack);
	}
	protected function mkENV() {
		$ENV = array();
		galaxy::extract_to($_ENV, $ENV, EXTR_REFS | EXTR_OVERWRITE);
		$data = get_object_vars($_ENV['g']);
		foreach($data as $key => $val) {
			if(is_array($val)) {
				galaxy::extract_to($val, $ENV, EXTR_REFS | EXTR_OVERWRITE);
			} else {
				$ENV[$key] = $val;
			}
		}
		return $ENV;
	}
	protected function readStyle($tplpath) {
		$style = @include($tplpath.'style.php');
		if(is_array($style)) {
			$style['imgdir'] or $style['imgdir'] = 'shell/default/images';
			$style['styleimgdir'] or $style['styleimgdir'] = $style['imgdir'];
			if($key=='styleimgdir' && empty($val)) $style[$key] = $val = 'shell/default/images';

			$datanew = array();
			foreach($style as $k => $v) {
				if(substr($k, -7, 7) == 'bgcolor') {
					$newkey = substr($k, 0, -7).'bgcode';
					$datanew[$newkey] = $this->setcssbackground($style, $k);
				}
			}
			$style = array_merge($style, $datanew);
			foreach($style as $key => $val) {
				defined(strtoupper($key)) or define(strtoupper($key), $val);
			}
			$this->writecsscache($style, $tplpath);
		}
	}
	protected function writecsscache($data, $tplpath) {
		$cssdata = '';
		foreach(array('_common' => array('css_common', 'css_append'),
				'_viewthread' => array('css_viewthread', 'css_viewthread_append'),
			'_float' => array('css_float', 'css_float_append'),
			) as $extra => $cssfiles) {
			$cssdata = '';
			foreach($cssfiles as $css) {
				$cssfile = $tplpath.'/'.$css.'.css';
				!file_exists($cssfile) && $cssfile = ROOT.'./shell/default/'.$css.'.htm';
				if(file_exists($cssfile)) {
					$cssdata .= file_get_contents($cssfile)."\n\n";
				}
			}
			$cssdata = preg_replace("/\{([A-Z0-9]+)\}/e", '\$data[strtolower(\'\1\')]', $cssdata);
			$cssdata = preg_replace("/<\?.+?\?>\s*/", '', $cssdata);
			$cssdata = !preg_match('/^http:\/\//i', $data['styleimgdir']) ? str_replace("url(\"$data[styleimgdir]", "url(\"../../$data[styleimgdir]", $cssdata) : $cssdata;
			$cssdata = !preg_match('/^http:\/\//i', $data['styleimgdir']) ? str_replace("url($data[styleimgdir]", "url(../../$data[styleimgdir]", $cssdata) : $cssdata;
			$cssdata = !preg_match('/^http:\/\//i', $data['imgdir']) ? str_replace("url(\"$data[imgdir]", "url(\"../../$data[imgdir]", $cssdata) : $cssdata;
			$cssdata = !preg_match('/^http:\/\//i', $data['imgdir']) ? str_replace("url($data[imgdir]", "url(../../$data[imgdir]", $cssdata) : $cssdata;
			$cssdata = preg_replace(array('/\s*([,;:\{\}])\s*/', '/[\t\n\r]/', '/\/\*.+?\*\//'), array('\\1', '',''), $cssdata);

			@mkdir(CACHEDIR.'style', 0777);
			if(@$fp = fopen(CACHEDIR.'style/'.$data['styleid'].$extra.'.css', 'w')) {
				fwrite($fp, $cssdata);
				fclose($fp);
			} else {
				exit('Can not write to cache files, please check directory ./cache/ and ./cache/style/ .');
			}
		}
	}
	protected function setcssbackground(&$data, $code) {
		$codes = explode(' ', $data[$code]);
		$css = $codevalue = '';
		for($i = 0; $i < count($codes); $i++) {
			if($i < 2) {
				if($codes[$i] != '') {
					if($codes[$i]{0} == '#') {
						$css .= strtoupper($codes[$i]).' ';
						$codevalue = strtoupper($codes[$i]);
					} elseif(preg_match('/^http:\/\//i', $codes[$i])) {
						$css .= 'url(\"'.$codes[$i].'\") ';
					} else {
						$css .= 'url("'.$data['styleimgdir'].'/'.$codes[$i].'") ';
					}
				}
			} else {
				$css .= $codes[$i].' ';
			}
		}
		$data[$code] = $codevalue;
		$css = trim($css);
		return $css ? 'background: '.$css : '';
	}

	protected function template($tplfile, $userpack = 'templates.lang.php', $tplpath = '', $tplcachepath = '', $cachelimit = '') {
		$tplpath = $tplpath != '' ? $tplpath : (defined("_TPLPath_") ? _TPLPath_ : '');
		$tplfile = file_exists($tplpath.$tplfile) ? $tplpath.$tplfile : ROOT.'shell/default/'.$tplfile;		
		$tplcachelimit = $cachelimit === '' ? (defined("_TPLCacheLimit_") ? _TPLCacheLimit_ : 0) : $cachelimit;
		defined("_TPLCachePath_") or define("_TPLCachePath_", '');
		@mkdir($tplcachepath !=='' ? $tplcachepath : _TPLCachePath_, 0777);
		$cachefile = ($tplcachepath !== '' ? $tplcachepath : _TPLCachePath_).str_replace(array('/', '.', '\\', ':'), '_', $tplfile.($userpack ? '.'.(is_array($userpack) ? implode($userpack, '-') : $userpack) : '')).'.php';
		$cachetime = @filemtime($cachefile);
		if (!file_exists($cachefile) || ($tplcachelimit && time() - $cachetime > $tplcachelimit) || @filemtime($tplfile) > $cachetime) {
			$tpl = new model_template;
			$tpl->userpack = $userpack;
			$tpl->template = file_get_contents($tplfile);
			$tpl->tplpath = $tplpath;
			$tpl->cachefile = $cachefile;
			$tpl->extraparms = ',\\\''.$tplpath.'\\\',\\\''.$tplcachepath.'\\\',\\\''.$userpack.'\\\',\\\''.$userpackpath.'\\\'';
			$this->readStyle($tplpath);
			return $tpl->compile();
		}
		return $cachefile;
	}
	
	protected function debuginfo() {
		$ret = array();
		$mtime = explode(' ', microtime());
		$ret['time'] = sprintf("%.4f", $mtime[1] + $mtime[0] - $_ENV['starttime']);
		$ret['queries'] = galaxy::getInstance()->db->querynum;
		return $ret;
	}

}

?>